#include "recbox.h"
#include "ui_recbox.h"
#include"recboxitem.h"

#include<QJsonObject>

RecBox::RecBox(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RecBox),
    row(2),
    col(4)
{
    ui->setupUi(this);

}

RecBox::~RecBox()
{
    delete ui;
}

void RecBox::recBoxUi(QJsonArray date, int row)
{
    if(2 == row)
    {
        this->row = row;
        col = 8;
    }
    else if(row!=2)
    {
        this->row = 1;
        //把下面的一列隐藏
        ui->recListDown->hide();
    }
    imageList = date;

    //将imageList进行分组
    count = imageList.size() / col;//共有多少组
    currIndex = 0; //默认显示第0组

    //在recBox控件中添加recBoxItem对象
    creatRecBoxItem();
}

void RecBox::creatRecBoxItem()
{
    //在创建新的一组item时先把上一次显示的删除，不然recBox会一直添加item
    //删除上层
    QList<RecBoxItem*> oldUpList = ui->recListUp->findChildren<RecBoxItem*>();
    for(auto &e : oldUpList)
    {
        ui->UpHLayout->removeWidget(e);
        delete e;//记得析构
    }
    //删除下层
    QList<RecBoxItem*> oldDownList = ui->recListDown->findChildren<RecBoxItem*>();
    for(auto &e : oldDownList)
    {
        ui->Down->removeWidget(e);
        delete e;//记得析构
    }

    int index = 0;
    for(int i = currIndex*col;i<currIndex*col + col;i++)
    {
        RecBoxItem* item = new RecBoxItem();

        //设置对应的文本和图片
        QJsonObject obj = imageList[i].toObject();
        item->setRecText(obj.value("text").toString());
        item->setRecImage(obj.value("path").toString());

        if(index >= col/2 && row == 2)
        {
            //recMusic
            ui->Down->addWidget(item);
        }
        else
        {
            //supplyMusic
            ui->UpHLayout->addWidget(item);
        }
        index++;

    }

}



void RecBox::on_btUp_clicked()
{
    //点击btUp
    currIndex--;
    if(currIndex<0)
    {
        //如果显示小于0就显示最后一组
        currIndex = count - 1;
    }
    creatRecBoxItem();
}

void RecBox::on_btDown_clicked()
{
    currIndex++;
    if(currIndex>count)
    {
        currIndex = 0;
    }
    creatRecBoxItem();
}
